<template>
  <div class="setup-view">
    <div>
      <div class="avatar-uploader">
        <Upload :default-url="imageUrl" @upload="avatarUpload" @remove="imageUrl = ''" />
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名:" prop="name">
          <el-input :value="$store.state.user.name" placeholder="请输入用户名" disabled />
        </el-form-item>
        <el-form-item label="旧密码:" prop="oldPwd">
          <el-input v-model="form.oldPwd" type="password" placeholder="请输入旧密码" />
        </el-form-item>
        <el-form-item label="新密码:" prop="newPwd1">
          <el-input v-model="form.newPwd1" type="password" placeholder="请输入新秘密" />
        </el-form-item>
        <el-form-item label="确认密码:" prop="newPwd2">
          <el-input v-model="form.newPwd2" type="password" placeholder="请确认密码" />
        </el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { update } from '@/api/user'
import Upload from '@/components/Upload'

export default {
  name: 'Setup',
  components: {
    Upload
  },
  data() {
    const { headImgUrl } = this.$store.state.user.userInfo
    return {
      imageUrl: headImgUrl, // 用户头像
      form: {
        oldPwd: '',
        newPwd1: '',
        newPwd2: ''
      },
      rules: {
        oldPwd: { required: true, message: '请输入旧密码', trigger: 'blur' },
        newPwd1: { required: true, message: '请输入新密码', trigger: 'blur' },
        newPwd2: {
          validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请再次输入密码'))
            } else if (value !== this.form.newPwd1) {
              callback(new Error('两次输入密码不一致!'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      }
    }
  },

  methods: {
    // 更改头像地址
    avatarUpload(url) {
      this.imageUrl = url
    },

    // 表单提交
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const obj = {
            headImgUrl: this.imageUrl,
            id: this.$store.state.user.userInfo.id
          }
          update({ ...this.form, ...obj }).then(() => {
            this.$message.success('修改成功')
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
@import './index';
</style>
